import vue from '@/main'

export function setUser(user){
    try{
        localStorage.setItem("user",JSON.stringify(user))
    }catch (e){

    }
}

export function setAvatar(avatar){
    let user = getUser()
    user.avatar = avatar
    setUser(user)
}

//用于保存主页的滚动位置
export function setHomeScroll(scrollTop){
    sessionStorage.setItem('homeScroll',scrollTop)
}

export function getHomeScroll(){
    return sessionStorage.getItem('homeScroll')
}

export function getUser(){
    let str = localStorage.getItem("user")
    if(str){
        try{
            return JSON.parse(str)
        }
        catch (e){
            //如果不是一个对象，则清空
            removeUser()
            return {}
        }
    }
    return {}
}

export function removeUser(){
    localStorage.removeItem("user")
}

import {refreshToken} from "@/api/user"

export function refreshUserToken(){
    return refreshToken().then(res=>{
        let user = getUser()
        if(user){
            user.token = res.data
            setUser(user)
        }
        return res
    })
}

export function getSearchHistory(keyword){
    let str = localStorage.getItem("searchHistory")
    if(str!==null&&str!==''&&str!==undefined){
        try{
            const histories = JSON.parse(str)
            //如果未传关键字，则返回所有历史记录
            if(keyword === ''||keyword===undefined||keyword===null){
                return histories
            }else {
                return histories.filter(history=>{
                    return history.keyword.includes(keyword)
                })
            }
        }
        catch (e){
            //如果不是一个对象，则清空并重新设置为[]
            removeSearchHistory()
            saveSearchHistory([])
            return []
        }
    }
    //将历史记录初始化为[]，仅在第一次获取时初始化
    saveSearchHistory([])
    return []
}

//设置历史记录时，历史记录应包含关键字的类型及selection[商品，品牌，分类]
export function pushSearchHistory({keyword,selection}){
    if(keyword===''||keyword===undefined||keyword===null)
        return
    let history = getSearchHistory()
    let index = history.map(history=>history.keyword).indexOf(keyword)
    if(index===-1){
        //往头部加入
        history.unshift({keyword,selection})
        //如果数组长度超过20，删除尾部
        while(history.length>20){
            history.pop()
        }
        saveSearchHistory(history)
    }
    //如果存在，则将其提到头部
    else{
        history.splice(index,1)
        history.unshift({keyword,selection})
        saveSearchHistory(history)
    }
}

export function saveSearchHistory(history){
    try{
        if(history instanceof Array)
            localStorage.setItem("searchHistory",JSON.stringify(history))
    }catch (e){
    }
}

export function removeSingleSearchHistory(keyword){
    let history = getSearchHistory()
    let index = history.map(history=>history.keyword).indexOf(keyword)
    if(index!==-1){
        history.splice(index,1)
        saveSearchHistory(history)
    }
}

export function removeSearchHistory(){
    localStorage.removeItem("searchHistory")
}